package com.sfeir.poc.portal.gui.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.ui.Composite;
import com.sfeir.poc.portal.gui.client.events.ApplicationEvent;
import com.sfeir.poc.portal.gui.client.events.ApplicationEventListener;
import com.sfeir.poc.portal.gui.client.events.ApplicationEventProvider;
import com.sfeir.poc.portal.gui.client.events.ApplicationEventType;

/**
 * 
 * this class is uses the events system in order to allow communication
 * between parts of the application
 * TODO:
 * 	-merge with EventAwareComposite
 *
 */
public class EventAwareComposite extends Composite implements ApplicationEventProvider, ApplicationEventListener{

	private final List<ApplicationEventListener> applicationListeners = new ArrayList<ApplicationEventListener>();

	public void addApplicationEventListener(final ApplicationEventListener listener) {
		if (!this.applicationListeners.contains(listener)) {
			this.applicationListeners.add(listener);

			if (listener instanceof ApplicationEventProvider) {
				((ApplicationEventProvider) listener).addApplicationEventListener(this); 
			}
		}
	}

	public void removeApplicationEventListener(final ApplicationEventListener listener) {
		if (this.applicationListeners.contains(listener)) {
			this.applicationListeners.remove(listener);

			if (listener instanceof ApplicationEventProvider) {
				((ApplicationEventProvider) listener).removeApplicationEventListener(this); 
			}
		}
	}

	public void fireActionEvent(final ApplicationEventType type, final Object eventContext) {
		final ApplicationEvent event = new ApplicationEvent(type, eventContext);

		for (ApplicationEventListener listener : this.applicationListeners) {
			listener.onActionFired(event);
		}
	}

	public void onActionFired(ApplicationEvent event) {

	}
}
